package com.example.servicetest;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.Random;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button addButton;
    private TextView result_text;
    private Button bindButton;
    private ComputeService.MyBinder myBinder;
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
             myBinder = (ComputeService.MyBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            myBinder = null;
        }
    };


    private Handler handler;

    @SuppressLint("HandlerLeak")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        addButton = findViewById(R.id.add_button);
        result_text = findViewById(R.id.show_result);
        bindButton = findViewById(R.id.bind_service);
        addButton.setOnClickListener(this);
        bindButton.setOnClickListener(this);
        handler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
            }
        };

    }

    @Override
    public void onClick(View v) {
         switch (v.getId()){
             case R.id.add_button:
                 if(myBinder != null){
                     int a = new Random().nextInt();
                     int b = new Random().nextInt();
                     myBinder.add(a,b,MainActivity.this);
                 }
                 break;
             case R.id.bind_service:
                 Intent intent = new Intent(this,ComputeService.class);
                 Bundle bundle = new Bundle();

                bindService(intent,serviceConnection,BIND_AUTO_CREATE);

                 break;
         }
    }


}
